//
//  UIViewExtension.swift
//  SaintfineCustomer
//
//  Created by Jack Lee on 2019/4/19.
//  Copyright © 2019 Saintfine. All rights reserved.
//

import UIKit

extension UIButton {
    public convenience init(frame: CGRect ,event:Event = Event.touchUpInside, actionHandler:@escaping((_ button:UIButton)->Void )) {
        self.init(frame:frame)
        addTarget(self, action: #selector(done), for: event)
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "actionHandler:".hashValue)
        objc_setAssociatedObject(self, key, actionHandler, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    @objc func done () {
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "actionHandler:".hashValue)
        if let actionHanlder = objc_getAssociatedObject(self, key) as? ((UIButton)->Void){
            actionHanlder( self )
        }
    }
}

extension UIView {
    func addTapGestureActionHandler(actionHandler:@escaping((_ gestureView:UIView)->Void ))  {
        isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapGesture(_:)))
        addGestureRecognizer(tap)
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "addTapGestureActionHandler:".hashValue)
        objc_setAssociatedObject(self, key, actionHandler, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    @objc func tapGesture(_ gesture:UITapGestureRecognizer) {
        let key : UnsafeRawPointer! = UnsafeRawPointer.init(bitPattern: "addTapGestureActionHandler:".hashValue)
        if let actionHanlder = objc_getAssociatedObject(self, key) as? ((UIView)->Void){
            actionHanlder(gesture.view!)
        }
    }
}


extension UIScrollView {
    // 返回顶部
    func scrollBackToTop(animated:Bool = true) {
       
        layoutIfNeeded()
        let desiredOffset = CGPoint(x: 0, y: -contentInset.top)
        setContentOffset(desiredOffset, animated: animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            self.setContentOffset(desiredOffset, animated: animated)
        }
    }
}

extension UIViewController {
    func Alert(title : String , msg: String , destructive:(() -> Void)? = nil ,  cancell:(() -> Void)? = nil )  {
        
        let vc:UIAlertController = UIAlertController(title: title, message: msg, preferredStyle:.alert)
        let ok:UIAlertAction = UIAlertAction.init(title: "OK", style: .destructive) { (ok) in
            if(destructive != nil){
                destructive!()
            }
        }
        let cancel:UIAlertAction = UIAlertAction.init(title: "取消", style: .cancel) { (cancel) in
            if(cancell != nil ){
                cancell!()
            }
        }
        vc.addAction(ok)
        vc.addAction(cancel)
        present(vc, animated: true, completion: nil)
    }
}

extension UIView {
    func removeAllsubViews()  {
        subviews.forEach {
            $0.removeFromSuperview()
        }
    }
}

extension Int {
    var floatValue:CGFloat {
        return CGFloat(self)
    }
}

extension CGFloat  {
    var intValue:Int {
        return Int(self)
    }
}

extension Array where Element: Equatable {
    mutating func remove(object: Element) {
        if let index = firstIndex(of: object) {
            remove(at: index)
        }
    }
}


extension Date {
    public static func currentTimestamp() -> Int {
        return   (Int) (NSDate(timeIntervalSinceNow:0).timeIntervalSince1970)
    }
}

extension UIColor {
    
    convenience init(r:Int,g:Int,b:Int,aplha:CGFloat = 1.0 ) {
        self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: aplha)
    }
    
    convenience init(hex: String) {
        let scanner = Scanner(string: hex)
        scanner.scanLocation = 0
        var rgbValue: UInt64 = 0
        scanner.scanHexInt64(&rgbValue)
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        self.init(red: CGFloat(r) / 0xff,green: CGFloat(g) / 0xff,blue: CGFloat(b) / 0xff, alpha: 1)
    }
    
    func toImage(size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
        UIGraphicsBeginImageContext(size);
        let context = UIGraphicsGetCurrentContext();
        context?.setFillColor(self.cgColor)
        context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image!;
    }
}
 
extension String {
    func image() ->UIImage? {
        return UIImage(named: self)
    }
}


